package com.sskj.spk.ui.activity;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.utils.EncryptUtils;
import com.sskj.common.base.App;
import com.sskj.common.base.HttpData;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.BaseHttpConfig;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.MainChangeTabBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.http.JsonCallBack;
import com.sskj.lib.util.APKVersionCodeUtils;
import com.sskj.lib.util.TipUtil;
import com.sskj.spk.BaseApplication;
import com.sskj.spk.Constant;
import com.sskj.spk.R;
import com.sskj.spk.bean.AppVersionBean;
import com.sskj.spk.presenter.MainActivityPresenter;
import com.sskj.spk.ui.fragment.AppUpDateFragment;

import java.io.UnsupportedEncodingException;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import sskj.lee.appupdatelibrary.BaseUpdateDialogFragment;
import sskj.lee.appupdatelibrary.BaseVersion;

import static com.sskj.lib.BaseHttpConfig.BASE_URL;
import static junit.framework.Assert.assertTrue;

@Route(path = RConfig.APP_MAIN)//主页面
public class MainActivity extends BaseActivity<MainActivityPresenter> {
    @BindView(R.id.bottomNavigationBar)
    BottomNavigationBar bottomNavigationBar;
    private List<Fragment> fragments;
    private int i = 0;
    @Autowired
    int pos;

    @Override
    protected int getLayoutResId() {
        return R.layout.app_activity_main;
    }

    @Override
    public MainActivityPresenter getPresenter() {
        return new MainActivityPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        BaseApplication.mainActivity = this;
        initFragment();
        initBottomNavBar();
        RxBus.getDefault().register(this);
        mPresenter.getSocket();
        checkVersion();
        test();
    }

    @Subscribe(code = RxBusCode.CHECK_VERSION, threadMode = ThreadMode.MAIN)
    public void checkVersion() {
        if (mPresenter != null) {
            i++;
            mPresenter.getNewVersion();
        }
    }

    @Subscribe(code = RxBusCode.LOGIN, threadMode = ThreadMode.MAIN)
    public void login() {
        String token = SPUtil.get(SPConfig.TOKEN, "");
        if (!TextUtils.isEmpty(token)) {
            OkGo.<HttpData<UserData>>get(BASE_URL + "/Home/Personal/get_user_info")
//                    .params("id", id)
                    .execute(new JsonCallBack<HttpData<UserData>>() {
                        @Override
                        public void onSuccess(Response<HttpData<UserData>> response) {
                            HttpData<UserData> httpData = response.body();
                            if (httpData.getStatus() == BaseHttpConfig.OK) {
                                if (TextUtils.isEmpty(httpData.getData().getMobile())) {
                                    try {
                                        TipUtil.getTip(MainActivity.this, getString(R.string.app_mobile_first), false, () -> {
                                        }).show();
                                    } catch (Exception e) {

                                    }
                                }
                            }
                        }
                    });
        }
    }


    public void initBottomNavBar() {
        bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_DEFAULT);
        bottomNavigationBar.setBarBackgroundColor(R.color.mine_222d41);

        bottomNavigationBar.setActiveColor(R.color.apptabNormalColor)
                .setInActiveColor(R.color.app_99a)
                .addItem(new BottomNavigationItem(R.mipmap.hangqing_hover, App.INSTANCE.getString(R.string.appMainActivity0))
                        .setInactiveIcon(ContextCompat.getDrawable(MainActivity.this, R.mipmap.hangqing)))
                .addItem(new BottomNavigationItem(R.mipmap.bibi_hover, App.INSTANCE.getString(R.string.app_bb))
                        .setInactiveIcon(ContextCompat.getDrawable(MainActivity.this, R.mipmap.bibi)))
//                .addItem(new BottomNavigationItem(R.mipmap.trade_hover, App.INSTANCE.getString(R.string.appMainActivity1))
//                        .setInactiveIcon(ContextCompat.getDrawable(MainActivity.this, R.mipmap.trade)))
                .addItem(new BottomNavigationItem(R.mipmap.c2c_hover, App.INSTANCE.getString(R.string.app_c2c))
                        .setInactiveIcon(ContextCompat.getDrawable(MainActivity.this, R.mipmap.c2c)))
                .addItem(new BottomNavigationItem(R.mipmap.wd_hover, App.INSTANCE.getString(R.string.appMainActivity3))
                        .setInactiveIcon(ContextCompat.getDrawable(MainActivity.this, R.mipmap.wd)))
                .setFirstSelectedPosition(pos).initialise();
        setTabSelection(pos);
        bottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                setTabSelection(position);
            }

            @Override
            public void onTabUnselected(int position) {
            }

            @Override
            public void onTabReselected(int position) {
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeTab(MainChangeTabBean mainTabChange) {
        bottomNavigationBar.selectTab(mainTabChange.getPos());
    }

    public void onVersionDataSuccess(AppVersionBean versionBean) {
        if (versionBean == null) {
            return;
        }
        String verName = APKVersionCodeUtils.getVerName(this);
        versionBean.setViewStyle(BaseVersion.NOTIFYCATION_STYLE);
        if (APKVersionCodeUtils.compareVersion(versionBean.getVersion(), verName) == 1) {
            android.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            AppUpDateFragment appUpDateFragment = new AppUpDateFragment();//自定义UI
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseUpdateDialogFragment.INTENT_KEY, versionBean);
            appUpDateFragment.setArguments(bundle);
            fragmentTransaction.add(appUpDateFragment, "updateUI");
            fragmentTransaction.commitAllowingStateLoss();
        } else {
            if (i > 1) {
                ToastUtil.showShort("当前已是最新版本");
            }
        }
    }

    /*
     *初始化Fragment栈管理
     */

    public void initFragment() {
        fragments = new ArrayList<>();
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.APP_HANGQING).withString(Constant.CODE, "3c_usdt").navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.BIBI_FRAGMENT_MAIN).withString(Constans.CODE, "BTC/USDT").navigation());
//        fragments.add((Fragment) ARouter.getInstance().build(RConfig.LEVEL_FRAGMENT_MAIN).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.FABI_FRAGMENT).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.MINE_FRAGMENT_MAIN).navigation());
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        for (Fragment fragment : fragments) {
            transaction.add(R.id.frameLayout, fragment);
        }
        transaction.commit();
    }

    public void setTabSelection(int index) {
        // 开启一个Fragment事务
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(fragmentTransaction);
        fragmentTransaction.show(fragments.get(index));
        fragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param fragmentTransaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction fragmentTransaction) {
        for (Fragment fragment : fragments) {
            fragmentTransaction.hide(fragment);
        }
    }

    @Override
    protected void onDestroy() {
        mPresenter.closeWebSocket();
        super.onDestroy();
    }

    public void test() {
//        String message = "{\"username\":\"方盒强1\",\"mobile\":\"13321995977\",\"info\":[]}";
//        String s1 = null;
//        s1 = new String(EncryptUtils.encryptRSA2Base64(
//                message.getBytes(),
//                base64Decode(com.sskj.common.Constant.publicKey.getBytes()),
//                true,
//                "RSA/ECB/PKCS1Padding"
//        ));
//        Log.i("info",com.sskj.common.Constant.privateKey.length()+"<<");

//        String s = new String(EncryptUtils.decryptHexStringRSA(
//                com.sskj.common.Constant.data,
//                base64Decode(com.sskj.common.Constant.privateKey.getBytes()),
//                false,
//                "RSA/ECB/PKCS1Padding"
//        ));
//        Log.i("info", "info:::" + s);
    }
//
//    private static byte[] base64Decode(final byte[] input) {
//        return Base64.decode(input, Base64.NO_WRAP);
//    }
//
//    private static byte[] base64Encode(final byte[] input) {
//        return Base64.encode(input, Base64.NO_WRAP);
//    }

}
